package com.c3w.synchro.controller;

import com.c3w.synchro.common.upload.FileUpload;
import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * User: P.Lalonde
 * Date: 13-02-20
 */
@Controller
@RequestMapping("/uploadSubscriptions")
public class SubscriptionFileUploadController implements HandlerExceptionResolver {

    @RequestMapping(method = RequestMethod.POST)
    public String processForm(@ModelAttribute(value = "FORM") FileUpload form, BindingResult result) {
        if (!result.hasErrors()) {
            String filePath = System.getProperty("java.io.tmpdir") + "/" + form.getFile().getOriginalFilename();
            try (FileOutputStream outputStream = new FileOutputStream(new File(filePath))) {
                FileItem fileItem = form.getFile().getFileItem();
                outputStream.write(fileItem.get());
            } catch (Exception e) {
                System.out.println("Error while saving file");
            }
        }

        return "dashboard";
    }

    /**
     * Try to resolve the given exception that got thrown during on handler execution,
     * returning a ModelAndView that represents a specific error page if appropriate.
     * <p>The returned ModelAndView may be {@linkplain org.springframework.web.servlet.ModelAndView#isEmpty() empty}
     * to indicate that the exception has been resolved successfully but that no view
     * should be rendered, for instance by setting a status code.
     *
     * @param request   current HTTP request
     * @param response  current HTTP response
     * @param handler   the executed handler, or <code>null</code> if none chosen at the
     *                  time of the exception (for example, if multipart resolution failed)
     * @param exception the exception that got thrown during handler execution
     * @return a corresponding ModelAndView to forward to,
     *         or <code>null</code> for default processing
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
        Map<Object, Object> model = new HashMap<>();
        if (exception instanceof MaxUploadSizeExceededException) {
            model.put("errors", "File size should be less then " + ((MaxUploadSizeExceededException) exception).getMaxUploadSize() + " byte.");
        } else {
            model.put("errors", "Unexpected error: " + exception.getMessage());
        }

        model.put("FORM", new FileUpload());
        return new ModelAndView("dashboard", (Map) model);
    }
}
